package org.iartisan.maven.plugin.handle;

import freemarker.template.TemplateException;
import org.iartisan.maven.plugin.jdbc.DBUtil;
import org.iartisan.maven.plugin.jdbc.JdbcConnection;
import org.iartisan.maven.plugin.jdbc.MySQLTableHandler;
import org.iartisan.maven.plugin.jdbc.TableHandler;
import org.iartisan.maven.plugin.jdbc.bean.TableColumn;
import org.iartisan.maven.plugin.mavenconfig.BaseConfig;
import org.iartisan.maven.plugin.mavenconfig.DaoPackageConfig;
import org.iartisan.maven.plugin.mavenconfig.DataSourceConfig;
import org.iartisan.maven.plugin.mavenconfig.TableConfig;
import org.iartisan.maven.plugin.template.TemplateParse;
import org.iartisan.maven.plugin.utils.FileUtil;
import org.iartisan.maven.plugin.utils.StringUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * dao 代码生成
 *
 * @author King
 * @since 2017/9/15
 */
public class DaoGenerateHandler extends BaseGenerateHandler {

    private static final String MODEL_PACKAGE = "modelPackage";

    private static final String DAO_PACKAGE = "daoPackage";

    private static final String DAO_IMPL_PACKAGE = "daoImplPackage";

    private static final String TABLE_NAME = "tableName";

    private static final String MODEL_SUFFIX = "modelSuffix";

    static void doGenerate(TemplateParse templateParse, BaseConfig baseConfig, TableConfig tableConfig, DataSourceConfig dataSourceConfig, DaoPackageConfig daoConfig) throws SQLException, ClassNotFoundException, IOException, TemplateException, IllegalAccessException {
        logger.info("开始生成DAO层代码");
        if (tableConfig == null) {
            logger.error("请添加tableConfig配置");
            return;
        }
        if (dataSourceConfig == null) {
            logger.error("请添加daoConfig配置");
            return;
        }
        //判断数据库类型
        String dbType = dataSourceConfig.getDbType();
        Connection connection = JdbcConnection.getConnection(dataSourceConfig);
        if ("mysql".equals(dbType)) {
            TableHandler mySQLTableHandler = new MySQLTableHandler(connection);
            String[] tableNames = tableConfig.getTableNames().split(",");
            for (String tableName : tableNames) {
                logger.info("开始生成表[" + tableName + "]代码");
                Map<String, Object> dataMap = new HashMap<String, Object>();
                List<TableColumn> tableColumnList = mySQLTableHandler.getTableFields(tableName);
                //获取import packages
                Map<String, String> map = new HashMap<String, String>();
                for (TableColumn column : tableColumnList) {
                    map.put(column.getJavaType(), column.getJavaType());
                }
                List<String> importPackages = new ArrayList<String>();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    importPackages.add(DBUtil.getImportPackage(entry.getKey()));
                }
                dataMap.put(IMPORT_PACKAGES, importPackages);
                //获取
                String className = DBUtil.getTableBeanName(tableName, false);
                dataMap.put(BEAN_NAME, className);
                dataMap.put(BEAN_ATTRIBUTES, tableColumnList);
                dataMap.put(AUTHOR, baseConfig.getAuthor());
                dataMap.put(TABLE_NAME, tableName);
                //Model代码
                String modelPackage = daoConfig.getModelPackage();
                dataMap.put(MODEL_SUFFIX, daoConfig.getModelSuffix());
                if (StringUtil.isNotEmpty(modelPackage)) {
                    dataMap.put(MODEL_PACKAGE, modelPackage);
                    String modelContent = templateParse.render("model/Model.ftl", dataMap);
                    FileUtil.writeToFile(className + (StringUtil.isNotEmpty(daoConfig.getModelSuffix()) ? daoConfig.getModelSuffix() : "") + ".java", FileUtil.getFilePath(baseConfig.getDirectory(), modelPackage), modelContent);
                }
                //DAO
                String daoPackage = daoConfig.getDaoPackage();
                if (StringUtil.isNotEmpty(daoPackage)) {
                    dataMap.put(DAO_PACKAGE, daoPackage);
                    String daoContent = templateParse.render("dao/Dao.ftl", dataMap);
                    if (StringUtil.isNotEmpty(baseConfig.getOrm()) && baseConfig.getOrm().equals(BaseConfig.ORM.mybatis_plus.getCode())) {
                        FileUtil.writeToFile(className + "Mapper.java", FileUtil.getFilePath(baseConfig.getDirectory(), daoPackage), daoContent);
                    } else if (StringUtil.isNotEmpty(baseConfig.getOrm()) && baseConfig.getOrm().equals(BaseConfig.ORM.querydsl.getCode())) {
                        FileUtil.writeToFile(className + "Mapper.java", FileUtil.getFilePath(baseConfig.getDirectory(), daoPackage), daoContent);
                    } else {
                        FileUtil.writeToFile(className + "DAO.java", FileUtil.getFilePath(baseConfig.getDirectory(), daoPackage), daoContent);
                        //daoImpl
                        String daoImplPackage = daoPackage + ".impl";
                        dataMap.put(DAO_IMPL_PACKAGE, daoImplPackage);
                        String daoImplContent = templateParse.render("dao/impl/DaoImpl.ftl", dataMap);
                        FileUtil.writeToFile(className + "DAOImpl.java", FileUtil.getFilePath(baseConfig.getDirectory(), daoImplPackage), daoImplContent);
                    }
                }
                String xmlMapper = daoConfig.getMapperXmlPackage();
                if (StringUtil.isNotEmpty(xmlMapper)) {
                    //mapper 代码
                    String mapperContent = templateParse.render("mapper/Mapper.ftl", dataMap);
                    FileUtil.writeToFile(className + "Mapper.xml", FileUtil.getFilePath(baseConfig.getDirectory(), daoConfig.getMapperXmlPackage()), mapperContent);
                }
            }
        }
    }
}
